package com.zb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.constant.NetworkConstant;
import com.zb.entity.*;
import com.zb.exception.SMSException;
import com.zb.extend.NetworkEmpRelationExtend;
import com.zb.mapper.ZjNetworkEmpRelationMapper;
import com.zb.mobile.NetworkEmpMobileVo;
import com.zb.result.PageUtil;
import com.zb.service.*;
import com.zb.util.MobileNetworkSmsUtil;
import com.zb.view.ViewNetworkEmpAccount;
import com.zb.view.ViewNetworkEmpDetail;
import com.zb.vo.NetworkEmpVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 网点人员关联表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-10-18
 */
@Service
public class ZjNetworkEmpRelationServiceImpl extends ServiceImpl<ZjNetworkEmpRelationMapper, ZjNetworkEmpRelation> implements ZjNetworkEmpRelationService {
    @Resource
    private ZjNetworkEmpRelationMapper networkEmpRelationMapper;
    @Resource
    private ZjNetworkService networkService;
    @Resource
    private ViewNetworkEmpAccountService viewNetworkEmpAccountService;
    @Resource
    private ViewNetworkEmpDetailService viewNetworkEmpDetailService;
    @Resource
    private ZjNetworkEmpFieldValService networkEmpFieldValService;
    @Resource
    private ZjNetworkEmpAuthenFieldValService networkEmpAuthenFieldValService;

    // 保存服务商负责人
    @Override
    public void saveNetworkManager(Long custAccId, Long networkId, Long networkEmpId) {
        ZjNetworkEmpRelation networkEmpRelation = networkEmpRelationMapper.getByNetworkIdAndNetworkEmpId(networkId, networkEmpId);
        // 查询服务商负责人
        Long id = networkEmpRelationMapper.getManagerByNetworkId(networkId);
        if (null != networkEmpRelation && Objects.equals(networkEmpRelation.getId(), id)) {
            return;
        }
        List<ZjNetworkEmpRelation> adds = new ArrayList<>();
        List<ZjNetworkEmpRelation> updates = new ArrayList<>();
        ZjNetworkEmpRelation empRelation = null;
        // 变更服务商原负责人
        empRelation = new ZjNetworkEmpRelation();
        empRelation.setId(id);
        empRelation.setManager(false);
        updates.add(empRelation);

        if (null == networkEmpRelation) {
            empRelation = new ZjNetworkEmpRelation();
            empRelation.setId(IdWorker.getId());
            empRelation.setCustAccId(custAccId);
            empRelation.setNetworkId(networkId);
            empRelation.setNetworkEmpId(networkEmpId);
            empRelation.setSuperManager(true);
            empRelation.setManager(true);
            empRelation.setQuit(false);
            adds.add(empRelation);
        } else {
            // 变更服务商新负责人
            empRelation = new ZjNetworkEmpRelation();
            empRelation.setId(networkEmpRelation.getId());
            empRelation.setManager(true);
            updates.add(empRelation);
        }
        if (CollectionUtil.isNotEmpty(adds)) this.saveBatch(adds);
        if (CollectionUtil.isNotEmpty(updates)) this.updateBatchById(updates);
    }

    // 根据服务人员ID & 网点ID 获取服务商负责人信息
    @Override
    public List<ZjNetworkEmpRelation> getManagerByNetworkEmpIdAndNetworkIds(Long networkEmpId, List<Long> networkIds) {
        if (CollectionUtils.isEmpty(networkIds)) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjNetworkEmpRelation> wrapper = new QueryWrapper<>();
        wrapper.eq("network_emp_id", networkEmpId)
                .in("network_id", networkIds)
                .eq("is_manager", true);
        return this.list(wrapper);
    }

    // 根据服务人员ID & 网点ID 删除服务商负责人信息
    @Override
    public void deleteByNetworkEmpAndNetworkIds(Long networkEmpId, List<Long> networkIds) {
        if (CollectionUtils.isEmpty(networkIds)) {
            return;
        }
        QueryWrapper<ZjNetworkEmpRelation> wrapper = new QueryWrapper<>();
        wrapper.eq("network_emp_id", networkEmpId)
                .in("network_id", networkIds);
        this.remove(wrapper);

    }

    // 保存服务商人员关联表
    @Override
    public void save(Long custAccId, Long networkEmpId, NetworkEmpVo networkEmpVo) {
        QueryWrapper<ZjNetworkEmpRelation> wrapper = new QueryWrapper<>();
        wrapper.select("id", "network_emp_id", "network_id");
        wrapper.eq("network_emp_id", null != networkEmpVo.getId() && networkEmpVo.getId() > 0? networkEmpVo.getId() : networkEmpId)
                .eq("cust_acc_id", custAccId);
        if (null != networkEmpVo.getNetworkId() && networkEmpVo.getNetworkId() > 0) {
            wrapper.in("network_id", 0, networkEmpVo.getNetworkId());
        }
        List<ZjNetworkEmpRelation> empRelations = this.list(wrapper);
        // 新增
        if (CollectionUtil.isEmpty(empRelations)) {
            ZjNetworkEmpRelation empRelation = new ZjNetworkEmpRelation();
            empRelation.setId(IdWorker.getId());
            empRelation.setCustAccId(custAccId);
            empRelation.setNetworkId(null == networkEmpVo.getNetworkId()? 0 : networkEmpVo.getNetworkId());
            empRelation.setNetworkEmpId(networkEmpId);
            empRelation.setSuperManager(null != networkEmpVo.getSuperManager() && networkEmpVo.getSuperManager());
            empRelation.setQuit(null != networkEmpVo.getQuit() && networkEmpVo.getQuit());
            empRelation.setManager(false);
            this.save(empRelation);
            return;
        }
        ZjNetworkEmpRelation empRelation = empRelations.stream().filter(f -> Objects.equals(f.getNetworkEmpId(), networkEmpVo.getId())).findFirst().orElse(null);
        // 修改
        if (null != empRelation) {
            empRelation.setNetworkEmpId(networkEmpId);
            if (null != networkEmpVo.getNetworkId() && networkEmpVo.getNetworkId() > 0){
                empRelation.setNetworkId(networkEmpVo.getNetworkId());
            }
            empRelation.setSuperManager(null != networkEmpVo.getSuperManager() && networkEmpVo.getSuperManager());
            empRelation.setQuit(null != networkEmpVo.getQuit() && networkEmpVo.getQuit());
            networkEmpRelationMapper.updateById(empRelation);
            return;
        }
        // 如果没有传服务商ID，表示仅更新服务人员
        if (null == networkEmpVo.getNetworkId() || networkEmpVo.getNetworkId() == 0) {
            empRelations.forEach(t -> {
                t.setQuit(null != networkEmpVo.getQuit() && networkEmpVo.getQuit());
                t.setSuperManager(null != networkEmpVo.getSuperManager() && networkEmpVo.getSuperManager());
            });
            this.updateBatchById(empRelations);
        } else {
            empRelation = empRelations.stream().filter(f -> f.getNetworkId() == 0).findFirst().orElse(null);
            if (null == empRelation) {
                empRelation = empRelations.stream().filter(f -> Objects.equals(f.getNetworkId(), networkEmpVo.getNetworkId())).findFirst().orElse(null);
            }
            if (null != empRelation) {
                empRelation.setNetworkId(networkEmpVo.getNetworkId());
                empRelation.setNetworkEmpId(networkEmpId);
                empRelation.setSuperManager(null != networkEmpVo.getSuperManager() && networkEmpVo.getSuperManager());
                empRelation.setQuit(null != networkEmpVo.getQuit() && networkEmpVo.getQuit());
                this.updateById(empRelation);
            } else {
                empRelation = new ZjNetworkEmpRelation();
                empRelation.setId(IdWorker.getId());
                empRelation.setCustAccId(custAccId);
                empRelation.setNetworkId(null == networkEmpVo.getNetworkId()? 0 : networkEmpVo.getNetworkId());
                empRelation.setNetworkEmpId(networkEmpId);
                empRelation.setSuperManager(null != networkEmpVo.getSuperManager() && networkEmpVo.getSuperManager());
                empRelation.setQuit(null != networkEmpVo.getQuit() && networkEmpVo.getQuit());
                empRelation.setManager(false);
                this.save(empRelation);
            }
        }
    }

    // 根据服务人员ID获取关联的服务商ID
    @Override
    public List<NetworkEmpRelationExtend> getnetworkIdByNetworkEmpIds(List<Long> networkEmpIds) {
        if (CollectionUtils.isEmpty(networkEmpIds)) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjNetworkEmpRelation> wrapper = new QueryWrapper<>();
        wrapper.in("network_emp_id", networkEmpIds)
                .eq("is_quit", false);
        List<ZjNetworkEmpRelation> relationList = this.list(wrapper);
        if (CollectionUtil.isEmpty(relationList)) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjNetwork> networkQueryWrapper = new QueryWrapper<>();
        networkQueryWrapper.select("id", "name", "is_disabled AS disabled");
        networkQueryWrapper.eq("is_disabled", false)
                .in("id", relationList.stream().map(ZjNetworkEmpRelation::getNetworkId).distinct().toList());
        List<ZjNetwork> networks = networkService.list(networkQueryWrapper);
        if (CollectionUtil.isEmpty(networks)) {
            return new ArrayList<>();
        }
        return relationList.stream().map(re -> {
            NetworkEmpRelationExtend extend = new NetworkEmpRelationExtend();
            BeanUtil.copyProperties(re, extend);
            extend.setNetwork(networks.stream().filter(f -> Objects.equals(f.getId(), re.getNetworkId())).map(ZjNetwork::getName).findFirst().orElse(""));
            return extend;
        }).toList();
    }

    // 根据服务商ID删除服务人员
    @Override
    public void deleteBatchByNetworkIds(List<Long> networkIds) {
        if (CollectionUtils.isEmpty(networkIds)) {
            return;
        }
        QueryWrapper<ZjNetworkEmpRelation> wrapper = new QueryWrapper<>();
        wrapper.in("network_id", networkIds);
        this.remove(wrapper);
    }

    // 根据服务人员ID & 服务商ID获取信息
    @Override
    public ZjNetworkEmpRelation getNetworkEmpIdAndNetworkId(Long networkEmpId, Long networkId) {
        QueryWrapper<ZjNetworkEmpRelation> wrapper = new QueryWrapper<>();
        wrapper.eq("network_id", networkId)
                .eq("network_emp_id", networkEmpId);
        return this.getOne(wrapper);
    }

    // 根据服务商人员ID获取服务商信息
    @Override
    public List<NetworkEmpRelationExtend> getByNetworkEmpId(Long networkEmpId) {
        List<Long> networkEmpIds = new ArrayList<>();
        networkEmpIds.add(networkEmpId);
        return getnetworkIdByNetworkEmpIds(networkEmpIds);
    }


    // 根据服务商ID获取服务商负责人信息
    @Override
    public NetworkEmpRelationExtend getManagerByNetworkId(Long networkId) {
        QueryWrapper<ZjNetworkEmpRelation> wrapper = new QueryWrapper<>();
        wrapper.in("network_id", networkId)
                .eq("is_manager", true);
        ZjNetworkEmpRelation empRelation = this.getOne(wrapper);
        if (null == empRelation) {
            return null;
        }
        NetworkEmpRelationExtend extend = new NetworkEmpRelationExtend();
        BeanUtil.copyProperties(empRelation, extend);
        ViewNetworkEmpAccount empAccount = viewNetworkEmpAccountService.getById(empRelation.getNetworkEmpId());
        if (null != empAccount) {
            extend.setManagerName(empAccount.getName());
        }
        return extend;
    }

    // 根据服务商ID&服务人员ID获取服务人员信息
    @Override
    public ZjNetworkEmpRelation getByNetworkIdAndNetworkEmpId(Long networkId, Long networkEmpId) {
        return networkEmpRelationMapper.getByNetworkIdAndNetworkEmpId(networkId, networkEmpId);
    }

    // 加入服务商
    @Override
    @Transactional
    public void joinNewtwork(AccounLoginInfo loginInfo, String inviteCode, NetworkEmpMobileVo empMobileVo) throws SMSException {
        NetworkInviteCodeVo inviteCodeVo = SmsVerificCodeService.checkJoinNetworkInviteCode(inviteCode, loginInfo.getPhone());
        // 删除邀请码
        SmsVerificCodeService.deleteJoinNetworkInviteCode(inviteCode, loginInfo.getPhone());
        ZjNetwork network = networkService.getById(inviteCodeVo.getNetworkId());
        Assert.isTrue(network.getTeamType() == NetworkConstant.NETWORK_TEAM_TYPE_1, "当前服务商团队模式为个人，不允许增加人员，如需增加人员，请升级服务商为团队模式");
        List<ZjNetworkEmpRelation> relationList = getByNetworkEmpId(inviteCodeVo.getCustAccId(), loginInfo.getNetworkEmpId());
        ZjNetworkEmpRelation empRelation = null;
        if (CollectionUtil.isNotEmpty(relationList)) {
            empRelation = relationList.stream().filter(f -> Objects.equals(f.getNetworkId(), inviteCodeVo.getNetworkId())).findFirst().orElse(null);
            if (null != empRelation) {
                Assert.isFalse(empRelation.getQuit(), "当前账号已加入服务商，并且当前账号处于离职状态");
                Assert.isFalse(true, "当前账号已加入服务商");
            } else {
                empRelation = relationList.stream().filter(f -> f.getNetworkId() == 0).findFirst().orElse(null);
                if (null != empRelation) {
                    empRelation.setNetworkId(inviteCodeVo.getNetworkId());
                    this.updateById(empRelation);
                }
            }
        }
        if (null == empRelation) {
            empRelation = new ZjNetworkEmpRelation();
            empRelation.setId(IdWorker.getId());
            empRelation.setCustAccId(inviteCodeVo.getCustAccId());
            empRelation.setNetworkId(inviteCodeVo.getNetworkId());
            empRelation.setNetworkEmpId(loginInfo.getNetworkEmpId());
            empRelation.setSuperManager(false);
            empRelation.setManager(false);
            empRelation.setQuit(false);
            this.save(empRelation);
        }
        // 工程师自定义字段
        networkEmpFieldValService.save(loginInfo.getCustAccId(), loginInfo.getNetworkEmpId(), empMobileVo.getFieldVals());
        // 工程师认证字段
        networkEmpAuthenFieldValService.save(loginInfo.getCustAccId(), loginInfo.getNetworkEmpId(), empMobileVo.getAuthorFieldVals());
    }

    // 获取服务商移动端人员列表
    @Override
    public Map<String, Object> getNetworkMobileEmpList(AccounLoginInfo loginInfo, SelectVo selectVo) {
        PageUtil.setPageLimitMobile(selectVo);
        List<ViewNetworkEmpDetail> networkEmpPageSelect = viewNetworkEmpDetailService.getNetworkEmpPageSelect(loginInfo.getNetworkId(), selectVo);

        return PageUtil.pageList(selectVo.getPage(), selectVo.getLimit(), 0L, networkEmpPageSelect.stream().map(e -> {
            return new SelectEmpVo(e.getId(), null, e.getAccountPhone(), e.getAccountName());
        }).toList());
    }

    // 根据商家ID&服务人员ID获取服务商负责人信息
    @Override
    public List<ZjNetworkEmpRelation> getManagerByCustAccIdAndNetworkEmpId(Long custAccId, Long networkEmpId) {
        QueryWrapper<ZjNetworkEmpRelation> wrapper = new QueryWrapper<>();
        wrapper.select("id", "network_id", "network_emp_id", "is_super_manager", "is_manager", "is_quit")
                .eq("cust_acc_id", custAccId).eq("network_emp_id", networkEmpId).eq("is_manager", true);
        return this.list(wrapper);
    }

    // 根据商家ID&服务人员ID获取所关联的服务商
    @Override
    public List<ZjNetworkEmpRelation> getByNetworkEmpId(Long custAccId, Long networkEmpId) {
        QueryWrapper<ZjNetworkEmpRelation> wrapper = new QueryWrapper<>();
//        wrapper.select("id", "network_id", "network_emp_id", "is_super_manager", "is_manager", "is_quit")
//                .eq("cust_acc_id", custAccId).eq("network_emp_id", networkEmpId);
        wrapper.eq("cust_acc_id", custAccId).eq("network_emp_id", networkEmpId);
        return this.list(wrapper);
    }
}
